﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using System.Xml;

namespace DocMreoLiteVersion
{
    public static class CSettings
    {

        public static class SaleContractSettings
        {
            /// <summary>
            /// Признак печати договора
            /// </summary>
            public static bool IsPrintNumberContract = true;
        }

        
        public static String PathDB = null;
        public static Dictionary<String, List<String>>  RegionsCityDictionary = new Dictionary<string, List<string>>();
        
        public static void LoadSettings()
        {
            var xml = new XmlDocument();
            xml.Load("AppSetting.xml");
            XmlElement xmlApplication = xml.GetElementsByTagName("Application").OfType<XmlElement>().First();

            XmlElement xmlSettings = xmlApplication.GetElementsByTagName("Settings").OfType<XmlElement>().First();
            XmlElement xmlSettingsDocuments = xmlApplication.GetElementsByTagName("SettingsDocuments").OfType<XmlElement>().First();

            XmlElement dbLocate = xmlSettings.GetElementsByTagName("DBLocate").OfType<XmlElement>().First();
            XmlElement dbSaleContract = xmlSettingsDocuments.GetElementsByTagName("SaleContract").OfType<XmlElement>().First();


            PathDB = dbLocate.GetAttribute("Path");
            SaleContractSettings.IsPrintNumberContract = Boolean.Parse(dbSaleContract.GetAttribute("PrintNumberContract"));
            

            //Чтение регионов из xml
            const String FileName = "Database\\Regions\\rocid.xml";

            if (File.Exists(FileName))
            {
                try
                {
                    RegionsCityDictionary.Clear();
                    LoadRegionXml(FileName);

                }
                catch (Exception err)
                {
                    MessageBox.Show(String.Format("Ошибка чтения БД регионов с сообщением: \n {0}",
                        err.Message + err.StackTrace));
                }
            }

        }


        public static void SaveSettings()
        {

            var xml = new XmlDocument();
            xml.Load("AppSetting.xml");
            XmlElement xmlApplication = xml.GetElementsByTagName("Application").OfType<XmlElement>().First();

            XmlElement xmlSettings = xmlApplication.GetElementsByTagName("Settings").OfType<XmlElement>().First();
            XmlElement xmlSettingsDocuments = xmlApplication.GetElementsByTagName("SettingsDocuments").OfType<XmlElement>().First();

            XmlElement dbLocate = xmlSettings.GetElementsByTagName("DBLocate").OfType<XmlElement>().First();
            XmlElement dbSaleContract = xmlSettingsDocuments.GetElementsByTagName("SaleContract").OfType<XmlElement>().First();


            dbLocate.SetAttribute("Path", PathDB);
            dbSaleContract.SetAttribute("PrintNumberContract", SaleContractSettings.IsPrintNumberContract.ToString());

            xml.Save("AppSetting.xml");

        }

        private static void LoadRegionXml(String fileName)
        {
            try
            {
                var xml = new XmlDocument();
                xml.Load(fileName);

                XmlElement rocidXmlElement = xml.GetElementsByTagName("rocid").OfType<XmlElement>().First();

                List<XmlElement> xmlRegionElement =
                    rocidXmlElement.GetElementsByTagName("region")
                        .OfType<XmlElement>().Where(element => element.GetElementsByTagName("country_id").OfType<XmlElement>().First().InnerText == "3159").AsEnumerable().ToList();

                RegionsCityDictionary.Clear();
                foreach (var element in xmlRegionElement)
                {

                    String nameRegion = element.GetElementsByTagName("name").OfType<XmlElement>().First().InnerText;
                    List<XmlElement> cityXmlElements =
                        rocidXmlElement.GetElementsByTagName("city")
                            .OfType<XmlElement>()
                            .Where(
                                melement =>
                                    melement.GetElementsByTagName("region_id").OfType<XmlElement>().First().InnerText ==
                                    element.GetElementsByTagName("region_id").OfType<XmlElement>().First().InnerText)
                            .AsEnumerable()
                            .ToList();

                    List<String> cityList = new List<string>();
                    foreach (var cityElement in cityXmlElements)
                    {
                        cityList.Add(cityElement.GetElementsByTagName("name").OfType<XmlElement>().First().InnerText);
                    }

                    RegionsCityDictionary.Add(nameRegion, cityList);
                }
            }
            catch (Exception err)
            {
                throw new Exception(String.Format("{0} \n {1}", err.Message, err.StackTrace));
            }
        }

    }
}
